<template>
    <el-main>
        <el-card class="box-card-c">
            <el-container class="chat-container">
                <el-header class="card-header">
                </el-header>
                <el-divider border-style="dashed" />
                <el-main class="chat-main">
                    <div v-for="(message, index) in messages" :key="index" class="message">
                        <el-row :justify="message.sender === userName ? 'end' : 'start'">
                            <el-col v-if="message.sender !== userName" :span="2" class="avatar-column-ai">
                                <el-avatar :size="32"
                                    src="https://img0.baidu.com/it/u=1889131064,3154324134&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=800" />
                            </el-col>
                            <el-col :span="16">
                                <div class="message-content" :class="{ 'my-message': message.sender === userName }">
                                    {{ message.content }}
                                </div>
                                <div class="message-meta">{{ message.sender }} • {{ message.time }}</div>
                            </el-col>
                        </el-row>
                    </div>
                </el-main>
                <el-footer class="chat-footer">
                    <el-button @click="toggleMode">{{ currentMode === 'gpt' ? '切换到AI代理' : '切换到GPT' }}</el-button>
                    <textarea v-model="newMessage" placeholder="请输入您的问题,Shift + Enter换行,Enter发送"
                        @keydown="handleKeydown" class="message-input"></textarea>
                    <el-button class="send-button" type="primary" :loading="isLoading" v-if="!isLoading"
                        @click="sendMessage">发送</el-button>
                    <el-button class="send-button" type="primary" :loading="true" v-else>加载中</el-button>
                </el-footer>
            </el-container>
        </el-card>
    </el-main>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue';

const messages = ref([]);
const newMessage = ref('');
const apiKey = '2a7c5bcde839dfa4fa428b526079f7f2.EgyNq2YCa6TbMJzx';
let userName = ref(localStorage.getItem('user_name'));
const isLoading = ref(false);


const changeBackground = inject('changeBackground');
const changeFont = inject('changeFont');

// 定义背景和字体选项
const backgroundData = [
    {
        value: 'light-mode',
        label: '亮色模式',
    },
    {
        value: 'dark-mode',
        label: '暗色模式',
    },
    {
        value: 'blue-mode',
        label: '蓝色模式',
    },
];

const fontData = [
    {
        value: 'default-font',
        label: '默认字体',
    },
    {
        value: 'serif-font',
        label: '衬线字体',
    },
    {
        value: 'sans-serif-font',
        label: '无衬线字体',
    },
];
const currentMode = ref('gpt'); // 当前模式

const toggleMode = () => {
    currentMode.value = currentMode.value === 'gpt' ? 'aiagent' : 'gpt';
};

const sendMessage = async () => {
    if (newMessage.value.trim() !== '') {
        const message = {
            content: newMessage.value,
            sender: userName.value,
            time: new Date().toLocaleTimeString(),
        };

        messages.value.push(message);
        const responseData = await handleUserInput(message.content);
        messages.value.push(responseData);
        newMessage.value = '';
    }
};

const handleUserInput = async (content) => {
    // 如果当前模式是 AI Agent，处理相关命令
    if (currentMode.value === 'aiagent') {
        const backgroundCommand = backgroundData.find(option => content.includes(option.label));
        const fontCommand = fontData.find(option => content.includes(option.label));

        if (backgroundCommand) {
            changeBackground(backgroundCommand.value);
            return { content: `背景已更改为 ${backgroundCommand.label}`, sender: 'AI助手', time: new Date().toLocaleTimeString() };
        } else if (fontCommand) {
            changeFont(fontCommand.value);
            return { content: `字体已更改为 ${fontCommand.label}`, sender: 'AI助手', time: new Date().toLocaleTimeString() };
        } else {
            return { content: "抱歉，我没有理解你的命令。", sender: 'AI助手', time: new Date().toLocaleTimeString() };
        }
    } else {
        // GPT 模式处理逻辑（与之前相同）
        const url = 'https://open.bigmodel.cn/api/paas/v4/chat/completions';
        const data = {
            messages: [
                {
                    role: 'user',
                    content: content
                }
            ],
            model: "glm-4-flash",
        };

        try {
            isLoading.value = true; // 设置为加载中
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                },
                body: JSON.stringify(data)
            });

            if (!response.ok) {
                throw new Error('API请求失败');
            }

            const responseData = await response.json();
            return { content: responseData.choices[0].message.content, sender: 'AI助手', time: new Date().toLocaleTimeString() };
        } catch (error) {
            console.error('Error:', error);
            return { content: "发生错误，请重试。", sender: 'AI助手', time: new Date().toLocaleTimeString() };
        } finally {
            isLoading.value = false; // 设置为非加载状态
        }
    }
};

const handleKeydown = (event) => {
    if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        sendMessage();
    }
};
</script>

<style scoped>
body {
    background: linear-gradient(135deg, #0d0e20, #1e1e2f);
    /* 渐变背景 */
    color: Black;
    /* 文字颜色，以提高对比度 */
}

.box-card-c {
    margin-top: 1%;
    margin-bottom: 20px;
    background-color: rgba(255, 255, 255, 0.1);
    /* 使用透明度使卡片有个半透明的效果 */
    border-radius: 10px;
    /* 卡片圆角 */
}

.chat-container {
    height: 80vh;
    backdrop-filter: blur(10px);
    /* 背景模糊效果 */
}

.card-header,
.chat-footer {
    background-color: rgba(0, 255, 255, 0.8);
    /* 半透明背景 */
    border-radius: 10px;
    /* 圆角 */
}

.chat-main {
    padding: 20px;
    overflow-y: auto;
    border-radius: 5px;
}

.message {
    margin-bottom: 10px;
}

.message-content {
    background-color: rgba(255, 255, 255, 0.2);
    /* 消息背景色为半透明 */
    padding: 10px;
    border-radius: 4px;
    color: black;
    /* 消息文字颜色 */
}

.my-message {
    background-color: #9af8a0;
    /* 发送的消息背景色设置为绿色 */
}

.message-meta {
    font-size: 12px;
    color: #ccc;
    /* 文字颜色设置为淡灰色 */
}

.chat-footer {
    display: flex;
    align-items: center;
    padding: 10px;
}

.message-input {
    flex: 1;
    margin-right: 10px;
    padding: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    resize: none;
    /* 防止用户调整大小 */
    background-color: rgba(255, 255, 255, 0.7);
    /* 输入框背景颜色 */
    color: black;
    /* 输入框文字颜色 */
}

.send-button {
    font-size: 16px;
    /* 调整字体大小 */
    padding: 10px 20px;
    /* 增加内边距 */
    height: auto;
    /* 适应内容自动高度 */
}

.avatar-column-ai {
    padding-right: 10px;
    /* AI头像与信息框的间距较小 */
}

.message-received .message-content {
    background-color: #b3d8ff;
    /* 接收的消息使用不同的背景色 */
}
</style>